package com.jiyongjun.component.exception.parser;

import com.jiyongjun.component.enums.LogConstant;
import com.jiyongjun.component.enums.LogResultTypeEnum;
import com.jiyongjun.component.exception.BizException;
import org.apache.dubbo.rpc.Invocation;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * <h2></h2>
 * <h3>描述：</h3>
 *
 * @author yongjun.jyj
 * @since 2022/6/13 18:54
 */
@Component("defaultBizExceptionParser")
public class BizExceptionParser implements ExceptionParser{
    @Override
    public boolean isMatch(Throwable throwable) {
        return BizException.class.isAssignableFrom(throwable.getClass())
                || IllegalArgumentException.class.isAssignableFrom(throwable.getClass());
    }

    @Override
    public ExceptionParseResult handle(Invocation invocation, Throwable throwable) {
        ExceptionParseResult exceptionParseResult = new ExceptionParseResult();
        exceptionParseResult.setRaw(throwable);
        exceptionParseResult.setExceptionType(LogResultTypeEnum.BIZ_EXCEPTION.getCode());
        exceptionParseResult.setMsgCode(LogConstant.DEFAULT_BIZ_EXCEPTION_CODE);
        exceptionParseResult.setMsgInfo(exceptionParseResult.getMsgInfo());

        if (throwable instanceof BizException) {
            BizException bizException = (BizException) throwable;
            exceptionParseResult.setMsgCode(bizException.getMsgCode());
            exceptionParseResult.setPayload(bizException.getPayload());
        }

        return exceptionParseResult;
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 20;
    }

}
